
;; 一键运行脚本

(defvar my/run-file-type-alist nil
  "可运行文件类型列表")
(setq my/run-file-type-alist
      '(("el" . (eval-buffer))

        ("c" . (if my/is-win
                   '(("gcc" :filename "-o a.exe" "& a.exe" "& pause" "& rm a.exe"))
                 '(("gcc" :filename "-o a.exe" "&& ./a.exe && rm a.exe"))
                 ))
        ("cpp" . (if my/is-win
                     '(("g++" :filename "-o a.exe" "& a.exe" "&pause" "& rm a.exe"))
                   '(("g++" :filename "-o a.exe" "&& ./a.exe && rm a.exe"))
                   ))
        ("zig" . '(("zig" "run" :filename "& pause")))

        ("py" . '(("python" :filename "& pause")))

        ("js" . '(("node" :filename "& pause")))
        ("ts" . '(("deno" "run" :filename "&pause")))

        ("scm" . '(("scheme" "--script" :filename "& pause")))
        ("ss" . '(("scheme" "--script" :filename "& pause")))

        ("html" . '(((if my/is-win "start" "xdg-open") :filename)))
        ))

(defun my/run-current-buffer ()
  "编译与运行当前buffer文件中的代码"
  (interactive)
  (when (buffer-modified-p)
    (save-buffer))
  (let* ((abs-path-file-name (buffer-file-name))
         (file_name (file-name-nondirectory (buffer-file-name)))
         (ext_name (file-name-extension file_name))
         (arglist (cdr (assoc ext_name my/run-file-type-alist)))
         ;; shell-command和call-process会使用dufault-directory变量作为工作目录
         (default-directory (file-name-directory abs-path-file-name))
         (cmd nil)
         )
    (if arglist
        (progn
          (setq-local arglist (eval arglist))
          (dolist (spec arglist)
            (while spec
              (setq-local cmd
                          (concat cmd
                                  (if cmd " " "")
                                  (cond ((eq (car spec) :filename) file_name)
                                        ((eq (car spec) :cwd) default-directory)
                                        (t (eval (car spec))))))
              (setq-local spec (cdr spec)))
            (message cmd)
            (if my/is-win
                (call-process-shell-command
                 (concat "start cmd.exe /C \"" cmd));;  " & pause & exit\""))
              ;;(shell-command cmd)
              (async-shell-command cmd))
            (setq-local cmd nil)))
      (message "没有指定类型的命令参数！！！"))))

(provide 'my/coderunner)
